import {
  defineComponent,
  ref,
} from 'vue'

import {
  ElButton,
  ElDialog,
  ElMessage,
} from 'element-plus'

import { createForm, isField, onFieldInit } from '@formily/core'
import Upload from '@/formily-components/Upload'

import SchemaForm from '@/components/SchemaForm'
import usePageTable from '@/hooks/usePageTable'
import {
  doReviewer,
  getAuditsList,
  getReviewersList,
} from '@/api/scholarship'
import type { AwardReview } from '@/types/scholarship'
import DictTag from '@/components/DictTag/index.vue'
import { reviewStatus } from '@/utils/staticDict'

export default defineComponent({
  setup() {
    const ReviewStatus = ref(reviewStatus)
    const form = createForm<AwardReview>({
      effects() {
        onFieldInit('layout.reviewResult', (field) => {
          if (isField(field))
            field.dataSource = ReviewStatus.value.splice(1, 2)
        })
      },
    })
    const title = ref('')
    const open = ref(false)

    const handleView = async (row: AwardReview) => {
      form.setValues({ ...row, reviewerId: null }, 'overwrite')
      const data = await getReviewersList({ roleKey: (Number(row.reviewerLevel) || 0) + 1 })
      form.setFieldState('layout.reviewerId', (state) => {
        state.dataSource = data.map(item => ({
          label: item.userName,
          value: item.userId,
        }))
      })
      open.value = true
      title.value = '审核'
    }

    /** 列表逻辑 */
    const {
      Table,
      handleSearch,
      QueryForm,
    } = usePageTable<AwardReview>(
      {
        fields: [
          {
            key: 'reviewResult',
            title: '审核状态',
            type: 'Select',
            enums: ReviewStatus.value,
          },
        ],
        initValues: {
          reviewResult: '待审核',
          pageSize: 10,
          pageNum: 1,
        },
        getList: getAuditsList,

      },
      [
        {
          key: 'applicationAwardType',
          title: '奖学金类型',
        },
        {
          key: 'nickName',
          title: '学生姓名',
        },
        {
          key: 'applicationDate',
          title: '申请时间',
        },

        {
          key: 'reviewResult',
          title: '审核状态',
          render: row => <DictTag value={row.reviewResult} options={ReviewStatus.value} type="tag" showValue={true} />,
        },
        {
          key: 'operate',
          title: '操作',
          render: row => (
            <>
              <ElButton link type="primary" icon="Edit" onClick={() => handleView(row)}>审核</ElButton>
            </>
          ),
        },
      ],
    )
    void handleSearch()

    const submit = () => {
      form.submit(async (values) => {
        const {
          reviewResult,
          reviewComment,
          recommendedReason,
          reviewerId,
          reviewer,
          reviewId,
          applicationId,
          reviewerLevel,
        } = values
        await doReviewer({
          reviewResult,
          reviewComment,
          recommendedReason,
          reviewerId,
          reviewer,
          reviewId,
          applicationId,
          reviewerLevel: reviewResult === '通过' ? ((Number(reviewerLevel) || 0) + 1) : reviewerLevel,
        })
        ElMessage.success('操作成功')
        open.value = false
        handleSearch()
      })
    }

    const schema = {
      type: 'object',
      properties: {
        layout: {
          'type': 'void',
          'x-component': 'FormLayout',
          'x-component-props': {
            labelWidth: 125,
          },
          'properties': {
            nickName: {
              'type': 'string',
              'title': '学生姓名',
              'x-component': 'Input',
              'x-decorator': 'FormItem',
              'x-disabled': true,
            },
            applicationAwardType: {
              'type': 'string',
              'title': '奖学金类型',
              'x-component': 'Input',
              'x-decorator': 'FormItem',
              'x-disabled': true,
            },
            baseSituation: {
              'type': 'string',
              'title': '基本情况',
              'x-component': 'Input.TextArea',
              'x-decorator': 'FormItem',
              'x-disabled': true,
            },
            studySituation: {
              'type': 'string',
              'title': '学习情况',
              'x-component': 'Input.TextArea',
              'x-decorator': 'FormItem',
              'x-disabled': true,
            },
            awardSituation: {
              'type': 'string',
              'title': '获奖情况',
              'x-component': 'Input.TextArea',
              'x-decorator': 'FormItem',
              'x-disabled': true,
            },
            file: {
              'type': 'string',
              'title': '附件',
              'x-component': 'Upload',
              'x-decorator': 'FormItem',
              'x-component-props': {
                fileType: [],
                fileSize: 20,
                limit: 10,
                tips: '提交申请材料（如申请书、成绩单、获奖证书等）',
              },
              'x-disabled': true,
            },
            reviewResult: {
              'type': 'string',
              'title': '审核结果',
              'x-component-props': {
                clearable: true,
                filterable: true,
              },
              'x-component': 'Select',
              'x-decorator': 'FormItem',
              'required': true,
            },

            reviewComment: {
              'type': 'string',
              'title': '审核原因',
              'x-component': 'Input.TextArea',
              'x-decorator': 'FormItem',
              'required': true,
              'x-reactions': {
                dependencies: ['.reviewResult'],
                when: '{{$deps[0] === \'不通过\'}}',
                fulfill: {
                  state: {
                    visible: true,
                  },
                },
                otherwise: {
                  state: {
                    visible: false,
                  },
                },
              },
            },
            recommendedReason: {
              'type': 'string',
              'title': '推荐理由',
              'x-component': 'Input.TextArea',
              'x-decorator': 'FormItem',
              'required': true,
              'x-reactions': {
                dependencies: ['.reviewResult'],
                when: '{{$deps[0] === \'不通过\'}}',
                fulfill: {
                  state: {
                    visible: false,
                  },
                },
                otherwise: {
                  state: {
                    visible: true,
                  },
                },
              },
            },
            reviewerId: {
              'type': 'string',
              'title': '审核人员',
              'x-component-props': {
                clearable: true,
                filterable: true,
              },
              'x-reactions': {
                dependencies: ['.reviewResult'],
                when: '{{$deps[0] === \'不通过\'}}',
                fulfill: {
                  state: {
                    visible: false,
                  },
                },
                otherwise: {
                  state: {
                    visible: true,
                  },
                },
              },
              'required': true,
              'x-component': 'Select',
              'x-decorator': 'FormItem',
            },
            reviewer: {
              'type': 'string',
              'x-reactions': {
                dependencies: ['.reviewerId#dataSource', '.reviewerId'],
                fulfill: {
                  state: {
                    value: '{{$deps[0] && $deps[0].find(i => i.value === $deps[1]) && $deps[0].find(i => i.value === $deps[1]).label}}',
                  },
                },
              },
            },
          },
        },
      },
    }
    return () => (
      <div class="p-2 md:p-4 h-full">
        <QueryForm />
        <Table />

        <ElDialog v-model={open.value} title={title.value} width="750px" append-to-body>

          {{
            default: () => <SchemaForm form={form} schema={schema} components={{ Upload }} />,
            footer: () => (
              <>
                <ElButton type="primary" onClick={submit}>
                  确 定
                </ElButton>
                <ElButton onClick={() => open.value = false}>
                  取 消
                </ElButton>
              </>
            ),
          }}
        </ElDialog>
      </div>
    )
  },
})
